<?php
/**
 * Created by PhpStorm.
 * User: ming
 * Date: 17-7-7
 * Time: 上午9:47
 */

class Server
{
    private $serv;

    public function __construct()
    {
        //构建Server对象
        $this->serv=new swoole_server("127.0.0.1", 9502);
        //设置运行时参数
        $this->serv->set(array(
            'worker_num'=>8,//worker进程数
            'daemonize'=>false,//daemonize => 1，加入此参数后，执行php server.php将转入后台作为守护进程运行
            'max_request' => 10000,
            'dispatch_mode' => 2,
            'debug_mode'=> 1
        ));
        //注册事件回调函数
        $this->serv->on('Start',array($this,'onStart'));
        $this->serv->on('Connect',array($this,'onConnect'));
        $this->serv->on('Receive',array($this,'onReceive'));
        $this->serv->on('close',array($this,'onclose'));
        //启动服务器
        $this->serv->start();
    }

    //onStart回调在server运行前被调用
    public function onStart($serv){
        echo "Start \n";
    }

    //onConnect在有新客户端连接过来时被调用 监听新的连接
    public function onConnect( $serv, $fd, $from_id ) {//回调连接
        $serv->send( $fd, "Hello {$fd}!" );
    }

    //onReceive函数在有数据发送到server时被调用 接收数据并处理
    public function onReceive( swoole_server $serv, $fd, $from_id, $data ) {//回调接收
        echo "Get Message From Client {$fd}:{$data}\n";
        $serv->send($fd, $data);
    }

    //onClose在有客户端断开连接时被调用
    public function onClose( $serv, $fd, $from_id ) {//回调关闭
        echo "Client {$fd} close connection\n";
    }

}
// 启动服务器
$server = new Server();